@extends('layouts.header')
@section('style')
    .c-green{
        color:green;
    }
    .red2{
        color:red;
    }
    #left-org-tree div{
        border-left:solid 1px black;
    }
@endsection
@section('content')
    <div class="page-container">
        <audio src="/admin/static/myfolder/mp3/tip.mp3" controls loop hidden id="player">浏览器不支持音频播放</audio>
        <div class="cl pd-5 bg-1 bk-gray">
            <b class="btn btn-primary radius ml-10" id="gaiyao_add">受理</b>
            <b class="btn btn-primary radius ml-10" id="edit_class">设置分类</b>
            <b class="btn btn-danger radius ml-10" onclick="del()">删除</b>
            <a class="btn btn-primary radius ml-10" target="thirdAll" href="all">全部样品</a>
            <a class="btn btn-primary radius r" href="javascript:location.replace(location.href);" title="刷新"><i class="Hui-iconfont">&#xe68f;</i></a>
            @foreach($thirds as $third)
                <div class="row cl mt-5">
                    <b class="col-sm-2 "><span class="r">{{$third->name}}：</span></b>
                    <b class="btn btn-primary radius col-sm-9 size-S export-new" onclick="export_new({{$third->id}})">拉取数据</b>
                    @if($third->canScan == 1)
                        <input type="text" placeholder="扫码拉取数据" class="input-text scan ml-10" data-third_id="{{$third->id}}" style="width: 50%;">
                    @endif
                </div>
            @endforeach
        </div>
        <div class="cl pd-5 bg-1 bk-gray form">
            <form class="form form-horizontal" id="form">
                <div class="row cl">
                    @if(count($thirds) > 1)
                    <label class="form-label col-xs-2">平台：</label>
                    <div class="formControls col-xs-7">
                        <select name="third_id" class="select2 input-text" >
                            <option value="" >--请选择--</option>
                            @foreach($thirds as $third)
                                <option value="{{$third->id}}" >{{$third->name}}</option>
                            @endforeach
                        </select>
                        <input type="hidden" name="third_name" placeholder="用于左侧栏筛选">
                    </div>
                    @endif
                </div>
                @foreach($orgTree as $third_id_name => $orgTreeItem)
                    @php list($third_id,$third_name) = explode('-',$third_id_name); @endphp
                    <div class="row cl orgs">
                        <label class="form-label col-sm-2"> {{$third_name}}送检单位： </label>
                        <div class="formControls col-sm-7">
                            <div class="mt-5">
                                <select class="select2 input-text" onchange="changeOrgId(this,{{$third_id}})">
                                    <option value="">--请选择--</option>
                                    @foreach($orgTreeItem as $item)
                                        <option value="{{data_get($item,'value','')}}">{{data_get($item,'tools',0) ? '●':''}}{{data_get($item,'label','')}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    <input type="hidden" name="third_org_name" placeholder="用于左侧栏筛选">
                @endforeach
                <div class="row cl">
                    <label class="form-label col-xs-2">送检日期：</label>
                    <div class="formControls col-xs-7">
                        <input type="date" name="send_time1" value=""  class="input-text Wdate" style="width:200px;">
                         - 
                        <input type="date" name="send_time2" value=""  class="input-text Wdate" style="width:200px;">
                        <span class="c-red ml-5 hidden" id="noData">未找到记录</span>
                    </div>
                </div>
                <div class="row cl tool">
                    <label class="form-label col-xs-2">待检样品：</label>
                    <div class="formControls col-xs-7">
                        <a class="ml-10" onclick="searchTool('',this)">全部</a>
                        @foreach($tools as $tool_name=>$count)
                            <a class="ml-10" onclick="searchTool('{{$tool_name}}',this)">{{$tool_name}}({{$count}})</a>
                        @endforeach
                        <input type="hidden" name="tool_name" value="">
                    </div>
                </div>
                <input type="hidden" name="third_org_id" value=''>
                <div class="row cl col-xs-offset-2">
                    <button class="btn btn-primary radius" type="reset" onclick="javascript:location.reload();">重置</button>
                    <span class="c-red">该搜索栏不能与左侧搜索栏同时使用！</span>
                </div>
            </form>
            <div class="row cl">
                <label class="col-xs-2 text-r">核对模式：</label>
                <span class="col-xs-7">
                    <label><input type="checkbox" id="check"> 开启</label>
                    <a class="btn btn-danger size-MINI radius ml-10" id="reset-check">重新核对</a>
                </span>
            </div>
            <div class="row cl">
                <label class="col-xs-2 text-r">扫码选择：</label>
                <span class="col-xs-7">
                    <input type="text" id="chose-third_id2" value="" class="input-text" placeholder="扫码选择">
                </span>
            </div>
        </div>
        <div class="mt-10">
            <div class="cl pd-5 bg-1 bk-gray col-sm-3" id="left-org-tree">
                <b class="c-red">单击显示下级，双击隐藏下级</b>
                @foreach($orgDj as $third_id_name => $orgItem)
                    @php list($third_id,$third_name) = explode('][',$third_id_name); @endphp
                    <div class="row cl ml-5 third_name" data-val="{{$third_name}}">
                        <b class="for-left-org-tree" > {{$third_name}}送检单位： </b>
                        @foreach($orgItem as $date => $orgTool)
                        <div class="ml-10 send_time" data-val="{{$date}}">
                            <b class="c-green for-left-org-tree">{{$date}}</b><br>
                            @foreach($orgTool as $third_org_id_name => $tools)
                                @php list($third_org_id,$third_org_name) = explode('][',$third_org_id_name); @endphp
                                <div class="ml-10 third_org_name" data-val="{{$third_org_name}}">
                                    <b class="c-green for-left-org-tree">{{$third_org_name}}：</b><br>
                                    <div class="ml-10">
                                        @foreach($tools as $tool_name=>$count)
                                            <div class="tool_name" data-val="{{$tool_name}}" >
                                                <a class="for-left-org-tree">{{$tool_name}}({{$count}})</a>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            @endforeach
                        </div>
                        @endforeach
                    </div>
                @endforeach
            </div>
            
            <div class=" col-sm-9">
                <div>
                    <label><input type="checkbox" id="showThirdInfo">显示拉取信息</label>
                </div>
                <div class="tb">
                    <table class="table table-border table-bordered table-hover table-bg table-responsive table-condensed" id="datatable">
                        <thead>
                            <tr class="text-c">
                                <th><input type="checkbox" id="checkAll"></th>
                                <th class="hidden tool_id">tool_id</th>
                                <th class="hidden std_id">std_id</th>
                                <th class="third_id hidden">third_id</th>
                                <th class="third_org_id hidden">送检单位ID</th>
                                <th class="third_name hidden ">数据拉取平台</th>
                                <th class="third_org_name hidden ">送检单位</th>
                                <th class="tool_name">样品名称</th>
                                <th class="from_third hidden">拉取样品名称</th>
                                <th>额定电压</th>
                                <th>分类</th>
                                <th>检验标准</th>
                                <th>本系统检验项目</th>
                                <th class="from_third hidden">拉取检验项目</th>
                                <th class="third_id2">RFID/自编号</th>
                                <th>生产厂家</th>
                                <th>规格型号</th>
                                <th>生产日期</th>
                                <th class="send_time1 send_time2">送检日期</th>
                                <th class="ctime">拉取日期</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($data as $item)
                            <tr class="text-c">
                                <td><input type="checkbox" value="{{$item->id}}"></td>
                                <td class="hidden tool_id">{{$item->tool_id}}</td>
                                <td class="hidden std_id">{{$item->std_id}}</td>
                                <td class="hidden third_id">{{$item->third_id}}</td>
                                <td class="hidden third_org_id">{{$item->third_org_id}}</td>
                                <td class="hidden third_name">{{$item->third_name}}</td>
                                <td class="hidden third_org_name">{{$item->third_org_name}}</td>
                                <td class="tool_name">{{$item->tool_name}}</td>
                                <td class="hidden from_third third_tool_name">{{$item->third_tool_name}}</td>
                                <td class="voltage">{{$item->voltage}}</td>
                                <td class="class">{{$item->class}}</td>
                                <td class="std_num">{{$item->std_num}}</td>
                                <td class="item_names">{{$item->item_names}}</td>
                                <td class="hidden from_third third_item_names">{{$item->third_item_names}}</td>
                                <td class="third_id2 {{$item->third_id2}}">{{$item->third_id2}}</td>
                                <td class="manufacturer">{{$item->manufacturer}}</td>
                                <td class="guige_xinghao">{{$item->guige_xinghao}}</td>
                                <td class="production_date">{{$item->production_date}}</td>
                                <td class="send_time">{{$item->send_time ? date('Y-m-d',strtotime($item->send_time)) : ''}}</td>
                                <td class="ctime">{{date('Y-m-d',strtotime($item->ctime))}}</td>
                                <td>
                                    <b class="btn btn-danger radius size-MINI" onclick="del({{$item->id}})">删除</b>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var table,nextOrgs=null,today='{{date('Y-m-d')}}',dbClickLastTime=0;
        $(function(){
            $.fn.dataTable.ext.errMode = 'throw';//datatable抛异常的方式，在console中输出，默认以alert的方式弹出
            table = $('#datatable').DataTable({
                // lengthMenu:[100,300,500,800,999],
                // pageLength: 100,
                dom:'iftr',
                paging:false,
                processing : true,//加载数据时候是否显示进度条
                language: { url: '/admin/lib/datatables/dataTables_Chinese_Lang.json' },
                // bStateSave:true
            });
            $('.scan').focus();
            // $('span:first','#tool_names').trigger('click'); //测试用
            // $('#checkAll').trigger('click'); //测试用
            // $('#edit_class').trigger('click'); //测试用
            // $('#gaiyao_add').trigger('click'); //测试用
            @if (!isAdmin())
                $('.export-new').each(function () {
                    $(this).trigger('click');
                })
            @endif
        })

        $('.scan').on('keypress',function () {
            if(event.which == 13){
                let params = {third_id:$(this).data('third_id'),third_id2:$(this).val()};
                ajax('post','',params,function (res) {
                    if(res == 1){
                        layer.msg('数据拉取成功,请手动刷新页面查看！');
                    }
                },0); 
            }
        })

        $('#gaiyao_add').on('click',function(){
            let orgId = '',
                third_org_name='',
                ids=[],
                third_id=0;
            var again = true;
            $('input:checkbox:checked','#datatable tbody').each(function () {
                let newOrgId = $(this).closest('tr').find('.third_org_id').text(),
                    newThirdId = $(this).closest('tr').find('.third_name').data("third_id");;
                if(orgId == ''){
                    third_id = newThirdId;
                    orgId = newOrgId;
                    third_org_name = $(this).closest('tr').find('.third_org_name').text();
                }else if(orgId != newOrgId){
                    layer.msg('送检单位不一致！');
                    again = false;
                    return false;
                }else if(third_id != newThirdId){
                    layer.msg('平台不一致！');
                    again = false;
                    return false;
                }
                ids.push($(this).val());
            })
            // console.log(ids);
            // return false;
            if (again == false) {
                return;
            }
            /*送检单位 start*/
                let orgNames = [];
                $('select option:selected','#org_form').each(function () {
                    if($(this).val()){
                        orgNames.push($(this).text());
                    }
                })
                if (orgNames.length == 0) {
                    orgNames.push(third_org_name);
                }
            /*送检单位 end*/
            let params = {
                    ids:ids,
                    org_names:orgNames,
                    third_id:third_id,
                    contract_id:"{{request('contract_id',0)}}",
                    _form_token:'{{csrf_form_token()}}'
                }
            ajax('post','add2Contract',params,function(res){
                let msg = res;
                if (res == 0) {
                    msg = '受理失败！'
                }else if(res == 1){
                    msg = '受理成功！';
                }
                layer.confirm(msg,function () {
                    if(res == 1){
                        location.reload();
                    }
                });
            });
        })

        function del(id=''){
            let ids = [];
            if (id) {
                ids.push(id);
            }else{
                $('tbody','#datatable').find('input:checkbox:checked').each(function () {
                    ids.push($(this).val());
                })
            }
            if (ids.length == 0) {
                layer.msg('请先选择要删除的数据！');
                return false;
            }
            ajax('post','del',{ids:ids},function(res){
                if (res > 0) {
                    location.reload();
                }
            });
        }
        function export_new(third_id) {
            let thirds = @json($thirds),
                params = JSON.parse(thirds[third_id]['params']);
            getThirdDjParam(third_id,params);
        }
        const getThirdDjParam = (thirdId,params) => {
            console.log(params);
            // return false;
            if(params.length == 0){
                getThirdDj(thirdId);
                return;
            }
            window.open('paramGetDj?third_id='+thirdId,'_blank');
        }

        const getThirdDj = (thirdId,formId='') => {
            let formData = formId != '' ? $('#'+formId).serialize() :'';
            formData += '&third_id='+thirdId;
            if (formId != '' && !$('#'+formId).valid()) {
                layer.msg("验证失败");
                return false;
            }
            ajax('post','',formData,getThirdDjBak,0);
            function getThirdDjBak(res) {
                let total = parseInt(res);
                if(!$.isNumeric(total)){
                    layer.confirm(res);
                    return false;
                }
                layer.confirm('导入样品量：'+total,{
                    btn:['刷新','关闭'],
                    btn1:function () {
                        location.reload();
                    }
                });
            }
        }

        //修改分类
        $('#edit_class').on('click',function(){
            let tool_name = '',tool_name2='',
                std_num = '',std_num2='',
                tool_id = '',std_id='',
                ids=[],stop=false;
            $('input:checkbox:checked','#datatable tbody').each(function (i) {
                // console.log(i);
                let trObj = $(this).closest('tr');
                tool_name2 = trObj.find('td.tool_name').text(); //工器具类型
                std_num2 = trObj.find('td.std_num').text(); //使用标准
                console.log(tool_name2);
                if(i == 0){
                    tool_name = tool_name2;
                    std_num = std_num2;
                    tool_id = trObj.find('td.tool_id').text();
                    std_id = trObj.find('td.std_id').text();
                }
                if (tool_name2 == '') {
                    console.log(tool_name2);
                    layer.msg('请先对照样品名称！！！');
                    stop = true;
                    return false;
                }
                if(tool_name2 != tool_name || std_num2 != std_num){
                    layer.msg('只有同一<b class="c-red">类型</b>和<b class="c-red">标准</b>的工器具才可以同时设置分类！');
                    stop = true;
                    return false;
                }
                ids.push($(this).val());
            })
            if(stop){
                return false;
            }
            if (ids.length == 0) {
                layer.msg('请选择样品！');
                return false;
            }
            
            ajax('get','/{{config('constant.name_admin')}}/myapi/getItem',{std_id:std_id,tool_id:tool_id,_form_token:'{{csrf_form_token()}}'},getItemBak,0)
            function getItemBak(res) {
                console.log(res);
                ids = ids.toString();
                let data_class = res.data_class;
                if (typeof data_class == 'object') {
                    let content='<form class="page-container form form-horizontal">'+
                                    '<div class="row cl">'+
                                        '<label class="form-label col-sm-2">请选择：</label>'+
                                        '<div class="formControls col-sm-10">'+
                                        '   <select id="select-class" class="input-text">';
                                            for(let i in data_class){
                                                content += '<option value="'+data_class[i]['id']+'">'+data_class[i]['val']+'</option>';
                                            }
                                            content += '<option value="0">/</option>'
                        content +=      '   </select>'+
                                        '</div>'+
                                    '</div>'+
                                    '<div class="row cl text-c">'+
                                        '<b class="btn btn-primary radius" onclick="setClass(\''+ids+'\')">确定</b>'+
                                        '<b class="btn btn-primary-outline radius ml-15" onclick="layer.close(thirdIndex)">关闭</b>'+
                                    '</div>'+
                                '</form>';
                    thirdIndex = layer.open({
                        type: 1, //类型
                        closeBtn: 1, //关闭按钮是否显示 1显示0不显示
                        title: '请求参数: ', //页面标题
                        shadeClose: true, //点击遮罩区域是否关闭页面
                        shade: 0.5,  //遮罩透明度
                        area: ['500px','300px'],  //弹出层页面比例
                        content: content,
                    })                  
                }
            }
        })
        const setClass = (ids)=>{
            let class_id = $('#select-class').val(),
                class_val = $('option:selected','#select-class').text();
            ajax('post','setClass',{ids:ids,class_id:class_id,class:class_val,_form_token:'{{csrf_form_token()}}'},setClassBak);
            function setClassBak(res) {
                if (res > 0) {
                    location.reload();
                }
            }
        }

        //select切换组织机构,数据之间是平行关系
        function changeOrgId(obj,third_id) {
            /*删除下面的下面兄弟元素 start*/
                let divRowIndex = $(obj).closest('div').index();
                $(obj).closest('div.formControls').find('div').each(function (index) {
                    if(index > divRowIndex){
                        $(this).remove();
                    }
                })
            /*删除下面的下面兄弟元素 end*/
            let orgId = $(obj).val();
            $('input[name=third_org_id]').val(orgId).trigger('change');
            if(orgId == ''){ //如果是请选择，触发上一级
                let parentSele = $(obj).closest('div').prev('div').find('select');
                if (parentSele.val()) {
                    parentSele.trigger('change'); //不是最顶级，触发上一级改变
                }else{
                    $(obj).closest('div').siblings('div').remove(); //如果是最顶级，删除所有兄弟元素
                }
                return false;
            }
            ajax('get','getOrgTree',{third_id:third_id,orgId:orgId},function (res) {
                if(res.length > 0){
                    let content = '<div class="mt-5">'+
                            '<select class="select2 input-text" onchange="changeOrgId(this,'+third_id+')">'+
                                '<option value="">--请选择--</option>';
                                for(let i in res){
                                    content += '<option value="'+res[i]['value']+'">' + (res[i]['tools'] == 1 ? '●' : '')+res[i]['label']+'</option>';
                                }
                            content += '</select>'+
                        '</div>';
                    $(obj).closest('div.formControls').append(content);
                }
            },0,0);
        }

        $('#showThirdInfo').on('change',function () {
            if ($(this).prop('checked') == true) {
                $('.from_third','#datatable').removeClass('hidden');
            }else{
                $('.from_third','#datatable').addClass('hidden');
            }
        })

        //监听form表单变化，在table中搜索对应数据
        $('input,select','form').on("change",function() {
            let name = $(this).attr('name'),
                val = $(this).val(),
                index = $('thead th.'+name,'#datatable').index();
            if (index > 0) {
                if (val == '') {
                    table.column(index).search('').draw();
                }else{
                    let regVal = '';
                    if (name == 'third_org_id') {
                        regVal = '-'+val+'-';
                    }else if (name == 'send_time1' || name == 'send_time2'){
                        $('#noData').addClass('hidden');
                        let starttime = $('input[name=send_time1]').val(),
                            endtime = $('input[name=send_time2]').val();
                        endtime = endtime == '' ? today : endtime; //如果是空值，取今天的日期
                        let dates = [];
                        table.column(index).data().each(function(val){
                            if(val >= starttime && val <= endtime){
                                if($.inArray(val,dates) == -1){
                                    dates.push(val);
                                }
                            }
                        })
                        if (dates.length == 0) {
                            $('#noData').removeClass('hidden');
                        }
                        regVal = dates.join('|');
                    }else{
                        regVal = '^'+val+'$';
                    }
                    table.column(index).search(regVal,true,false).draw();
                }
            }
        })

        $('#left-org-tree').on('click','.for-left-org-tree', function(event){
            var thisVal = $(this).data('val'),
                searchParams = {
                    third_name:'',
                    send_time1:'',
                    send_time2:'',
                    third_org_name:'',
                    tool_name:''
                };
            $('div.orgs').each(function(){
                $(this).find('select').first().val('').trigger('change');
            })
            $('.for-left-org-tree').removeClass('red2');
            $(this).addClass('red2');
            if ($(this).hasClass('for-left-org-tree') == true) { 
                //单击显示，双击隐藏
                let isDbClick = false,now = event.timeStamp;
                if (now - dbClickLastTime < 400) {
                    isDbClick = true;
                }
                dbClickLastTime = now;
                if(isDbClick == true){
                    $(this).closest('div').find('div').addClass('hidden');
                }else{
                    $(this).closest('div').find('div').removeClass('hidden');
                }
            }
            // console.log(searchParams);
            for (let name in searchParams) {
                 // console.log(name);
                let value = ''
                if(name == 'send_time1' || name == 'send_time2'){
                    let name2='send_time';
                    value= $(this).closest('div.'+name2).data('val');
                }else{
                    value = $(this).closest('div.'+name).data('val');
                }
                searchParams[name] = value==null?'':value;
            }
            // console.log(searchParams);
            for (let name in searchParams) {
                $('input[name='+name+']').val(searchParams[name]).trigger('change');
            }
        })

        function searchTool(tool_name='',obj){
            $(obj).closest('div').find('a').removeClass('red2');
            $(obj).addClass('red2');
            $('input[name=tool_name]').val(tool_name).trigger('change');
        }

        $('#chose-third_id2').on('keypress',function () {
            if (event.keyCode == 13) {
                var third_id2 = $(this).val(),
                    has = false;
                $('td.third_id2','#datatable tbody').each(function(){
                    if ($(this).text() == third_id2) {
                        has = true;
                        $(this).closest('tr').find('input:checkbox').prop('checked','checked');
                        toCheck(third_id2);
                        return false;
                    }
                })
                $(this).val('');
                if (has == false) {
                    $('#player')[0].play();
                    var plyerIndex = layer.confirm('找不到该样品！<br>扫码内容：'+third_id2,
                        {icon:5,title:'错误提示：',btn:['静音','取消']},
                        function () {
                        $('#player')[0].pause();
                    },function () {
                        $('#player')[0].pause();
                        layer.close(plyerIndex);
                    })
                }
            }
        })
        $('#check').on('change',function () {
            toCheck();
        })
        $('#reset-check').on('click',function () {
            layer.confirm('当前操作会将之前的核对过的样品<span class="c-red">清空</span>，您确定重新核对吗？',{btn:['确定','取消']},
                function () {
                    $('#check').prop('checked',true);
                    toCheck('',1);
            })
        })
        //核对
        function toCheck(third_id2='',reset=0){
            // console.log(222);
            let checked = $('#check').prop('checked');
            // console.log(checked);
            if (checked == true) {
                ajax('post','',{type:'check',reset:reset,third_id2:third_id2},function (data) {
                    // console.log(data);
                    if (reset == 1) {
                        $('tr input:checkbox','#datatable tbody').prop('checked',false);
                    }

                    var checkedNum = 0;
                    for(let i in data){
                        let third_id2 = data[i];
                        // console.log(third_id2);
                        let checked = $('tr','#datatable tbody').find('td.third_id2.'+third_id2).closest('tr').find('input:checkbox').prop('checked','checked');
                        if (checked.length > 0) {
                            checkedNum += 1;
                        }
                    }
                    let total = $('tr input:checkbox','#datatable tbody').length;
                    layer.msg('列表样品总数量：<span class="c-red">'+total+'</span>，<br>已核对样品数量：<span class="c-red">'+checkedNum+'</span>',{time:5000});
                        // console.log(checkedNum);

                },0,0);
            }else{
                $('input:checkbox:checked').prop('checked',false);
            }
        }

        //
        
    </script>

@endsection

